
# 判断企业用户有没有登录
from django.http import JsonResponse
from django.views import View

from apps.firmUser.models import FirmUser
from apps.user.models import User
from utils.jwtUtils import verify_jwt


class MyLoginView(View):

    def dispatch(self, request, *args, **kwargs):
        # Try to dispatch to the right method; if a method doesn't exist,
        # defer to the error handler. Also defer to the error handler if the
        # request method isn't on the approved list.
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed
        # 在这里进行token验证判断是否登录
        self.TokenVerification(request)

        if not request.user:
            return JsonResponse({"message":"没有权限"},status=401)

        return handler(request, *args, **kwargs)

    def TokenVerification(self,request):
        token = request.headers.get("Authorization")

        if token:
            ret = verify_jwt(token.split(' ')[1])
            if ret and ret.get('user_id'):
                try:
                    user = User.objects.get(id=ret.get('user_id'))

                except Exception as e:
                    request.user = None
                    return
                request.user = user
                return
        request.user = None


